import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import '../../../common/services/permission_service.dart';
import 'dart:io';
import 'dart:developer' as developer;

import 'index.dart';

/// 高德地图页面视图（原生地图版本）
/// 
/// 🎯 功能：
/// - 显示原生高德地图
/// - 位置搜索和选择
/// - 定位功能
/// - 查看模式和选择模式
class AmapPage extends StatelessWidget {
  const AmapPage({super.key});

  // 🔥 静态变量防重复权限请求（类级别）
  static bool _isRequestingPermission = false;
  
  // 🔥 页面关闭标志（用于显示遮罩）
  static final RxBool _isPageClosing = false.obs;

  // 创建稳定的原生地图视图（使用Hybrid Composition）
  Widget _buildStableMapView(AmapController mapController) {
    return PlatformViewLink(
      viewType: 'amap_flutter_map',
      surfaceFactory: (context, controller) {
        return AndroidViewSurface(
          controller: controller as AndroidViewController,
          gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
          hitTestBehavior: PlatformViewHitTestBehavior.opaque,
        );
      },
      onCreatePlatformView: (params) {
        final AndroidViewController viewController = PlatformViewsService.initSurfaceAndroidView(
          id: params.id,
          viewType: 'amap_flutter_map',
          layoutDirection: TextDirection.ltr,
          creationParams: <String, dynamic>{
            'initialLatitude': mapController.latitude.value,
            'initialLongitude': mapController.longitude.value,
          },
          creationParamsCodec: const StandardMessageCodec(),
          onFocus: () {
            params.onFocusChanged(true);
          },
        );
        
        // 监听平台视图创建完成
        viewController.addOnPlatformViewCreatedListener((int id) {
          developer.log('🗺️ 稳定地图视图创建成功，ViewID: $id', name: 'AmapPage');
          
          try {
            // 设置地图交互Channel
            mapController.setMapChannel(id);
            
            // 🔥 延迟执行权限检查，确保地图完全加载和controller状态设置完成
            Future.delayed(const Duration(milliseconds: 800), () {
              // 🔥 关键检查1：页面是否正在关闭
              if (AmapPage._isPageClosing.value) {
                developer.log('⚠️ 页面正在关闭，跳过地图初始化', name: 'AmapPage');
                return;
              }
              
              // 🔥 关键检查2：controller是否还存在
              if (!Get.isRegistered<AmapController>()) {
                developer.log('⚠️ AmapController已被删除，跳过权限检查', name: 'AmapPage');
                return;
              }
              
              final isViewMode = mapController.isViewModeRx.value;
              final hasIncomingLocation = mapController.hasIncomingLocationRx.value;
              
              developer.log('🔍 地图就绪状态检查:', name: 'AmapPage');
              developer.log('   - 查看模式: $isViewMode', name: 'AmapPage');
              developer.log('   - 有传入位置: $hasIncomingLocation', name: 'AmapPage');
              developer.log('   - 当前位置: ${mapController.currentLocation.value}', name: 'AmapPage');
              developer.log('   - 当前坐标: ${mapController.latitude.value}, ${mapController.longitude.value}', name: 'AmapPage');
              
              // 🔥 只有在非查看模式且没有传入位置参数时才请求权限并定位用户
              if (!isViewMode && !hasIncomingLocation) {
                developer.log('📍 地图已就绪，非查看模式且无传入位置，开始请求权限并定位用户', name: 'AmapPage');
                _requestLocationPermissionWithService();
              } else {
                developer.log('✅ 地图已就绪，跳过用户定位', name: 'AmapPage');
                developer.log('   原因: ${isViewMode ? "查看模式" : ""}${hasIncomingLocation ? "已有传入位置" : ""}', name: 'AmapPage');
                
                // 🔥 查看模式下确保地图移动到传入的位置
                if (isViewMode && hasIncomingLocation) {
                  final lat = mapController.latitude.value;
                  final lng = mapController.longitude.value;
                  if (lat != 0.0 || lng != 0.0) {
                    developer.log('🗺️ 查看模式：移动地图到传入位置 $lat, $lng', name: 'AmapPage');
                    mapController.moveMapToLocation(lat, lng);
                  }
                }
              }
            });
          } catch (e) {
            developer.log('💥 地图初始化异常: $e', name: 'AmapPage');
            // 移除snackbar提示，避免打扰用户
          }
          
          params.onPlatformViewCreated(id);
        });
        
        return viewController;
      },
    );
  }

  // 主视图（地图 + 搜索）
  Widget _buildView(AmapController controller) {
    return Stack(
      children: [
        // 地图主体
        Positioned.fill(
          child: _buildMapWidget(controller),
        ),
        
        // 🔥 查看模式下隐藏顶部搜索框
        if (!controller.isViewModeRx.value)
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Row(
                children: [
                  Expanded(
                    child: GetBuilder<AmapController>(
                      builder: (mapController) {
                        // 🔥 双重安全检查：确保Controller存在
                        if (!Get.isRegistered<AmapController>()) {
                          return Container(
                            decoration: BoxDecoration(
                              color: Colors.grey[100],
                              borderRadius: BorderRadius.circular(8),
                            ),
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                            child: const Text(
                              "搜索位置",
                              style: TextStyle(color: Colors.grey),
                            ),
                          );
                        }
                        
                        // 🔥 安全创建TextField
                        try {
                          return TextField(
                            controller: mapController.searchController,
                            decoration: const InputDecoration(
                              hintText: "搜索位置",
                              border: InputBorder.none,
                              prefixIcon: Icon(Icons.search),
                            ),
                            onChanged: mapController.onSearchChanged,
                            onSubmitted: mapController.onSearchSubmitted,
                          );
                        } catch (e) {
                          // Controller已被dispose，显示占位符
                          return Container(
                            decoration: BoxDecoration(
                              color: Colors.grey[100],
                              borderRadius: BorderRadius.circular(8),
                            ),
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                            child: const Text(
                              "搜索位置",
                              style: TextStyle(color: Colors.grey),
                            ),
                          );
                        }
                      },
                    ),
                  ),
                  Obx(() {
                    // 🔥 安全检查：确保Controller还存在
                    if (!Get.isRegistered<AmapController>()) {
                      return const SizedBox.shrink();
                    }
                    return controller.isSearching.value
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          )
                        : const SizedBox.shrink();
                  }),
                ],
              ),
            ),
          ),
        
        // 🔥 查看模式下隐藏搜索结果列表
        if (!controller.isViewModeRx.value)
          Positioned(
            top: 56, // 搜索框高度
            left: 0,
            right: 0,
            bottom: 0,
            child: Obx(() {
              // 🔥 安全检查：确保Controller还存在
              if (!Get.isRegistered<AmapController>()) {
                return const SizedBox.shrink();
              }
              return controller.showSearchResults.value
                  ? Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 4,
                            offset: const Offset(0, -2),
                          ),
                        ],
                      ),
                      child: ListView.separated(
                        itemCount: controller.searchResults.length,
                        separatorBuilder: (context, index) => const Divider(height: 1),
                        itemBuilder: (context, index) {
                          final result = controller.searchResults[index];
                          return ListTile(
                            leading: const Icon(Icons.location_on, color: Colors.red),
                            title: Text(result.title),
                            subtitle: result.subtitle.isNotEmpty ? Text(result.subtitle) : null,
                            trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                            onTap: () => controller.onSearchResultSelected(result),
                          );
                        },
                      ),
                    )
                  : const SizedBox.shrink();
            }),
          ),
      ],
    );
  }
  
  // 地图组件（使用原生高德地图）
  Widget _buildMapWidget(AmapController mapController) {
    // 只在Android平台显示原生地图
    if (Platform.isAndroid) {
      return Stack(
        children: [
          // 原生高德地图（使用稳定的Hybrid Composition）
          _buildStableMapView(mapController),
          
          // 坐标信息显示
          Positioned(
            bottom: 20,
            left: 20,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.7),
                borderRadius: BorderRadius.circular(8),
              ),
              child: GetBuilder<AmapController>(
                builder: (controller) {
                  if (!Get.isRegistered<AmapController>()) {
                    return const Text(
                      '0.000000, 0.000000',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontFamily: 'monospace',
                      ),
                    );
                  }
                  return Text(
                    '${controller.latitude.value.toStringAsFixed(6)}, ${controller.longitude.value.toStringAsFixed(6)}',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                      fontFamily: 'monospace',
                    ),
                  );
                },
              ),
            ),
          ),
          
          // 右下角重新定位按钮（查看模式下禁用）
          Positioned(
            bottom: 80,
            right: 20,
            child: GetBuilder<AmapController>(
              builder: (controller) {
                if (!Get.isRegistered<AmapController>()) {
                  return FloatingActionButton(
                    mini: true,
                    onPressed: null,
                    backgroundColor: Colors.grey.shade300,
                    child: Icon(Icons.location_searching, color: Colors.grey.shade600),
                  );
                }
                
                final isViewMode = controller.isViewModeRx.value;
                final isLocating = controller.currentLocation.value.contains("正在");
                
                return FloatingActionButton(
                  mini: true,
                  onPressed: isViewMode ? null : () {
                    // 优先使用原生地图定位
                    controller.startMapLocationSelf();
                  },
                  backgroundColor: isViewMode ? Colors.grey.shade300 : Colors.white,
                  child: isViewMode
                      ? Icon(Icons.visibility, color: Colors.grey.shade600)
                      : isLocating
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : const Icon(Icons.my_location, color: Colors.blue),
                );
              },
            ),
          ),
        ],
      );
    } else {
      // iOS或其他平台显示占位符
      return Container(
        color: Colors.grey[200],
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.map_outlined,
                size: 120,
                color: Colors.grey[400],
              ),
              const SizedBox(height: 16),
              Text(
                '地图功能仅在Android平台可用',
                style: TextStyle(
                  fontSize: 18,
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      );
    }
  }

  // 请求位置权限
  Future<void> _requestLocationPermissionWithService() async {
    // 🔥 防止重复调用
    if (AmapPage._isRequestingPermission) {
      developer.log('⚠️ 权限请求已在进行中，跳过重复调用', name: 'AmapPage');
      return;
    }
    
    try {
      AmapPage._isRequestingPermission = true;
      developer.log('🔐 开始请求位置权限...', name: 'AmapPage');
      
      // 🔥 检查Controller是否还存在
      if (!Get.isRegistered<AmapController>()) {
        developer.log('⚠️ AmapController已被删除，停止权限请求', name: 'AmapPage');
        return;
      }
      
      // 使用PermissionService请求位置权限
      final permissionService = Get.find<PermissionService>();
      
      // 请求位置权限
      final result = await permissionService.requestLocationPermission();
      
      // 🔥 再次检查Controller是否还存在
      if (!Get.isRegistered<AmapController>()) {
        developer.log('⚠️ AmapController在权限请求过程中被删除', name: 'AmapPage');
        return;
      }
      
      if (result.isGranted) {
        developer.log('✅ 位置权限获取成功', name: 'AmapPage');
        
        // 权限获取成功，开始定位
        final mapController = Get.find<AmapController>();
        mapController.onPermissionGranted();
      } else {
        developer.log('❌ 位置权限被拒绝', name: 'AmapPage');
        
        // 设置默认位置信息
        final mapController = Get.find<AmapController>();
        mapController.currentLocation.value = "位置权限被拒绝，请在设置中开启位置权限";
      }
    } catch (e) {
      developer.log('💥 权限请求异常: $e', name: 'AmapPage');
      
      // 🔥 检查Controller是否还存在再处理异常
      if (Get.isRegistered<AmapController>()) {
        // 处理权限请求异常
        final mapController = Get.find<AmapController>();
        mapController.currentLocation.value = "权限请求失败: $e";
      } else {
        developer.log('⚠️ Controller已删除，跳过异常处理', name: 'AmapPage');
      }
    } finally {
      AmapPage._isRequestingPermission = false; // 🔥 重置权限请求标记
    }
  }

  @override
  Widget build(BuildContext context) {
    final buildStartTime = DateTime.now().millisecondsSinceEpoch;
    developer.log('🏗️ =============== AmapPage build 开始 ===============', name: 'AmapPage');
    developer.log('🏗️ 开始时间戳: $buildStartTime', name: 'AmapPage');
    
    // 🔥 关键修复：立即重置页面关闭标志，防止黑屏遮罩显示
    AmapPage._isPageClosing.value = false;
    developer.log('✅ 重置页面关闭标志', name: 'AmapPage');
    
    // 🔥 添加帧渲染监听器，检测何时发生绘制
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final frameEndTime = DateTime.now().millisecondsSinceEpoch;
      developer.log('🎨 =============== AmapPage 帧渲染完成 ===============', name: 'AmapPage');
      developer.log('🎨 帧渲染时间戳: $frameEndTime', name: 'AmapPage');
      developer.log('🎨 帧渲染耗时: ${frameEndTime - buildStartTime}ms', name: 'AmapPage');
    });
    
    // 🔥 立即获取参数，避免时序问题 - 使用ModalRoute更可靠
    final Map<String, dynamic>? args = ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    final Map<String, dynamic>? getArgs = Get.arguments;
    
    developer.log('🔍 AmapPage build - ModalRoute.arguments: $args (类型: ${args.runtimeType})', name: 'AmapPage');
    developer.log('🔍 AmapPage build - Get.arguments: $getArgs (类型: ${getArgs.runtimeType})', name: 'AmapPage');
    
    // 🔥 优先使用ModalRoute参数，兜底使用Get.arguments
    final finalArgs = args ?? getArgs;
    developer.log('🎯 AmapPage build - 最终使用参数: $finalArgs', name: 'AmapPage');
    
    return GetBuilder<AmapController>(
      init: AmapController(initialArguments: finalArgs), // 🔥 直接传递参数
      id: "amap",
      dispose: (state) {
        // 🔥 确保Controller正确销毁
        developer.log('🗑️ AmapPage dispose 被调用', name: 'AmapPage');
      },
      builder: (controller) {
        return WillPopScope(
          onWillPop: () async {
            // 🔥 系统返回键触发：黑屏遮罩 → 隐藏地图 → 允许返回
            developer.log('🔙 =============== WillPopScope触发（系统返回键）===============', name: 'AmapPage');
            
            // 🎯 第0步：立即显示黑屏遮罩
            AmapPage._isPageClosing.value = true;
            await Future.delayed(const Duration(milliseconds: 16));
            
            // 🎯 第1步：隐藏地图
            if (Get.isRegistered<AmapController>()) {
              try {
                await controller.stopMapChannel();
              } catch (e) {
                developer.log('⚠️ 隐藏地图失败: $e', name: 'AmapPage');
              }
            }
            
            // 🎯 第2步：允许返回（标志会在下次打开页面时重置）
            return true;
          },
          child: Obx(() => Stack(
            children: [
              // 主要内容
              Scaffold(
                extendBodyBehindAppBar: false,
                appBar: AppBar(
                  backgroundColor: Colors.white,
                  elevation: 0,
                  centerTitle: true,
                  title: Obx(() {
                    if (!Get.isRegistered<AmapController>()) {
                      return const Text("地图", style: TextStyle(color: Colors.black));
                    }
                    return Text(
                      controller.isViewModeRx.value ? "查看位置" : "定位",
                      style: const TextStyle(color: Colors.black),
                    );
                  }),
                  leading: IconButton(
                    icon: const Icon(
                      Icons.arrow_back_ios,
                      color: Colors.black87,
                      size: 20,
                    ),
                    onPressed: () async {
                      // 🔥 AppBar返回按钮：黑屏遮罩 → 隐藏地图 → 返回
                      developer.log('🔙 =============== AppBar返回按钮点击 ===============', name: 'AmapPage');
                      
                      // 🎯 第0步：立即显示黑屏遮罩（防止返回动画期间看到页面内容）
                      AmapPage._isPageClosing.value = true;
                      await Future.delayed(const Duration(milliseconds: 16)); // 等待1帧确保遮罩显示
                      
                      // 🎯 第1步：隐藏地图
                      if (Get.isRegistered<AmapController>()) {
                        try {
                          await controller.stopMapChannel();
                        } catch (e) {
                          developer.log('⚠️ 隐藏地图失败: $e', name: 'AmapPage');
                        }
                      }
                      
                      // 🎯 第2步：触发返回（此时页面已黑屏，用户看不到闪烁）
                      // 标志会在下次打开页面时重置
                      Get.back();
                    },
                  ),
                  actions: [
                    Padding(
                      padding: const EdgeInsets.only(right: 8.0),
                      child: Obx(() {
                        if (!Get.isRegistered<AmapController>()) {
                          return ElevatedButton(
                            onPressed: () => Get.back(),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.grey.shade400,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(0),
                              ),
                              minimumSize: const Size(60, 36),
                            ),
                            child: const Text('返回'),
                          );
                        }
                        
                        return ElevatedButton(
                          onPressed: () async {
                            developer.log('🎯 =============== 确定/返回按钮点击 ===============', name: 'AmapPage');
                            
                            // 🎯 第0步：立即显示黑屏遮罩
                            AmapPage._isPageClosing.value = true;
                            await Future.delayed(const Duration(milliseconds: 16));
                            
                            // 🎯 第1步：隐藏地图
                            if (Get.isRegistered<AmapController>()) {
                              try {
                                await controller.stopMapChannel();
                              } catch (e) {
                                developer.log('⚠️ 隐藏地图失败: $e', name: 'AmapPage');
                              }
                            }
                            
                            // 🎯 第2步：触发返回（标志会在下次打开页面时重置）
                            if (controller.isViewModeRx.value) {
                              Get.back();
                            } else {
                              final locationData = {
                                'address': controller.currentLocation.value,
                                'latitude': controller.latitude.value,
                                'longitude': controller.longitude.value,
                              };
                              Get.back(result: locationData);
                            }
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: controller.isViewModeRx.value 
                                ? Colors.grey.shade400 
                                : const Color(0xFF8BC34A),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(0),
                            ),
                            minimumSize: const Size(60, 36),
                          ),
                          child: Text(controller.isViewModeRx.value ? '返回' : '确定'),
                        );
                      }),
                    ),
                  ],
                ),
                // 在AppBar下方添加当前位置信息显示
                body: Column(
                  children: [
                // 🗺️ 当前位置信息显示区域
                Container(
                  width: double.infinity,
                  color: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 定位状态指示器
                      Row(
                        children: [
                          Obx(() {
                            final isLocating = controller.currentLocation.value.contains("正在");
                            return AnimatedContainer(
                              duration: const Duration(milliseconds: 300),
                              width: 8,
                              height: 8,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: isLocating 
                                  ? Colors.orange
                                  : (controller.currentLocation.value.contains("失败") || controller.currentLocation.value.contains("默认"))
                                    ? Colors.red 
                                    : Colors.green,
                              ),
                            );
                          }),
                          const SizedBox(width: 8),
                          const Text(
                            "当前位置",
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const Spacer(),
                          // 🎯 定位精度指示
                          Obx(() {
                            if (!Get.isRegistered<AmapController>()) {
                              return const Icon(Icons.location_searching, size: 16, color: Colors.grey);
                            }
                            
                            final location = controller.currentLocation.value;
                            if (location.contains("高精度")) {
                              return const Icon(Icons.gps_fixed, size: 16, color: Colors.green);
                            } else if (location.contains("中等精度")) {
                              return const Icon(Icons.gps_not_fixed, size: 16, color: Colors.orange);
                            } else if (location.contains("低精度") || location.contains("精度较差")) {
                              return const Icon(Icons.gps_off, size: 16, color: Colors.red);
                            } else {
                              return const Icon(Icons.location_searching, size: 16, color: Colors.grey);
                            }
                          }),
                        ],
                      ),
                      const SizedBox(height: 8),
                      // 位置信息和重新定位按钮
                      Row(
                        children: [
                          Expanded(
                            child: Container(
                              padding: const EdgeInsets.all(12),
                              decoration: BoxDecoration(
                                border: Border.all(color: Colors.blue.shade300, width: 1),
                                borderRadius: BorderRadius.circular(8),
                                color: Colors.blue.shade50,
                              ),
                              child: Obx(() {
                                if (!Get.isRegistered<AmapController>()) {
                                  return const Text(
                                    "位置信息加载中...",
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500,
                                    ),
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                  );
                                }
                                
                                return Text(
                                  controller.currentLocation.value,
                                  style: const TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.w500,
                                  ),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                );
                              }),
                            ),
                          ),
                          const SizedBox(width: 12),
                          // 🎯 重新定位按钮（在查看模式下隐藏或修改功能）
                          Obx(() {
                            if (!Get.isRegistered<AmapController>()) {
                              return Container(
                                decoration: BoxDecoration(
                                  color: Colors.grey.shade300,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: const Padding(
                                  padding: EdgeInsets.all(12),
                                  child: Icon(
                                    Icons.location_searching,
                                    color: Colors.grey,
                                    size: 20,
                                  ),
                                ),
                              );
                            }
                            
                            final isViewMode = controller.isViewModeRx.value;
                            final isLocating = controller.currentLocation.value.contains("正在");
                            
                            return !isViewMode
                              ? Container(
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      colors: [Colors.blue.shade400, Colors.blue.shade600],
                                    ),
                                    borderRadius: BorderRadius.circular(8),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.blue.withOpacity(0.3),
                                        blurRadius: 4,
                                        offset: const Offset(0, 2),
                                      ),
                                    ],
                                  ),
                                  child: Material(
                                    color: Colors.transparent,
                                    child: InkWell(
                                      borderRadius: BorderRadius.circular(8),
                                      onTap: () {
                                        // 重新定位
                                        controller.requestLocationPermission();
                                      },
                                      child: Padding(
                                        padding: const EdgeInsets.all(12),
                                        child: AnimatedSwitcher(
                                          duration: const Duration(milliseconds: 300),
                                          child: isLocating
                                            ? const SizedBox(
                                                width: 20,
                                                height: 20,
                                                child: CircularProgressIndicator(
                                                  strokeWidth: 2,
                                                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                                ),
                                              )
                                            : const Icon(
                                                Icons.my_location,
                                                color: Colors.white,
                                                size: 20,
                                              ),
                                        ),
                                      ),
                                    ),
                                  ),
                                )
                              : Container(
                                  decoration: BoxDecoration(
                                    color: Colors.grey.shade300,
                                    borderRadius: BorderRadius.circular(8),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.grey.withOpacity(0.2),
                                        blurRadius: 4,
                                        offset: const Offset(0, 2),
                                      ),
                                    ],
                                  ),
                                  child: Padding(
                                    padding: const EdgeInsets.all(12),
                                    child: Icon(
                                      Icons.visibility,
                                      color: Colors.grey.shade600,
                                      size: 20,
                                    ),
                                  ),
                                );
                          }),
                        ],
                      ),
                    ],
                  ),
                ),
                    // 地图主体
                    Expanded(child: _buildView(controller)),
                  ],
                ),
              ),
              // 🔥 黑色遮罩层（返回时显示，防止看到页面闪烁）
              if (AmapPage._isPageClosing.value)
                Container(
                  color: Colors.black,
                  child: const Center(
                    child: CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  ),
                ),
            ],
          )),
        );
      },
    );
  }
}
